package com.shinhye.elephantsafe;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import com.shinhye.elephantsafe.service.AutoKillService;
import com.shinhye.elephantsafe.ui.SetStatusRelativeLayout;
import com.shinhye.elephantsafe.utils.SystemInfoUtils;

public class ProcManagerSettingActivity extends Activity {

	private SetStatusRelativeLayout ssrl_showsystemprocess;
	private SetStatusRelativeLayout ssrl_lock_killprocess;
	private SharedPreferences sp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_procmanager_setting);
		sp = getSharedPreferences("Setting", MODE_PRIVATE);
		
		//设置是否显示系统进程
		ssrl_showsystemprocess = (SetStatusRelativeLayout) findViewById(R.id.ssrl_showsystemprocess);
		boolean showsys = sp.getBoolean("showsystemprocess", true);
		ssrl_showsystemprocess.setChecked(showsys);
		
		ssrl_showsystemprocess.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ssrl_showsystemprocess.setChecked(!ssrl_showsystemprocess.isChecked());
				Editor editor = sp.edit();
				editor.putBoolean("showsystemprocess", ssrl_showsystemprocess.isChecked());
				editor.commit();
			}
		});
		
		//设置锁屏清理进程是否开启 -- 在SplashActivity中判断是否开启
		ssrl_lock_killprocess = (SetStatusRelativeLayout) findViewById(R.id.ssrl_lock_killprocess);
		final Intent autoKillIntent = new Intent(this, AutoKillService.class);
		
		String autoKillName = AutoKillService.class.getName();
		boolean autokill = sp.getBoolean("autokill", false);
		boolean isAutoKillRunning = SystemInfoUtils.isServiceRunning(this, autoKillName);
		
		if(autokill) {
			ssrl_lock_killprocess.setChecked(true);
			if(!isAutoKillRunning)
				startService(autoKillIntent);
		} else {
			ssrl_lock_killprocess.setChecked(false);
			if(isAutoKillRunning)
				stopService(autoKillIntent);
		}
		
		ssrl_lock_killprocess.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Editor editor = sp.edit();
				if(ssrl_lock_killprocess.isChecked()) {
					ssrl_lock_killprocess.setChecked(false);
					editor.putBoolean("autokill", false);
					stopService(autoKillIntent);
				} else {
					ssrl_lock_killprocess.setChecked(true);
					editor.putBoolean("autokill", true);
					startService(autoKillIntent);
				}
				editor.commit();
			}
		});

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		//在activity结束时设置偏好设置会出问题，因为执行super.onDestory()后，会先执行另一个页面的onActivityResult()方法，导致出错
//		Editor editor = sp.edit();
//		editor.putBoolean("showsystemprocess", ssrl_showsystemprocess.isChecked());
//		editor.commit();
	}
}
